package com.rex.saas.utils;


import lombok.extern.slf4j.Slf4j;
import org.quartz.CronExpression;

import java.text.ParseException;
import java.util.Date;

@Slf4j
public class CronValidator {

    public static boolean matches(String cronExpression, Date date) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            return cron.isSatisfiedBy(date);
        } catch (IllegalArgumentException | ParseException e) {
            // 这里处理cron表达式不合法的情况
            log.error("matches cron表达式不合法, cron:{}, date:{}", cronExpression, date);
            return false;
        }
    }

    public static Date getNextValidTime(String cronExpression, Date date) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            return cron.getNextValidTimeAfter(date);
        } catch (IllegalArgumentException | ParseException e) {
            // 这里处理cron表达式不合法的情况
            log.error("getNextValidTime cron表达式不合法, cron:{}, date:{}", cronExpression, date);
            return null;
        }
    }

    public static Date getNextInvalidTimeAfter(String cronExpression, Date date) {
        try {
            CronExpression cron = new CronExpression(cronExpression);
            return cron.getNextInvalidTimeAfter(date);
        } catch (IllegalArgumentException | ParseException e) {
            // 这里处理cron表达式不合法的情况
            log.error("getNextInvalidTimeAfter cron表达式不合法, cron:{}, date:{}", cronExpression, date);
            return null;
        }
    }

    public static void main(String[] args) {
        String cronExpression = "0 0 8-12,15-17  * * ?"; // 每天中午12点触发
        Date now = new Date();
        boolean matches = matches(cronExpression, now);
        System.out.println("当前时间是否匹配CRON表达式: " + matches);
        System.out.println("下次运行时间: " + getNextValidTime(cronExpression, now));
        System.out.println("下次不匹配时间: " + getNextInvalidTimeAfter(cronExpression, now));

    }
}